package ui.swing.tree.eventhandle;

import java.awt.BorderLayout;
import java.io.IOException;

import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;

public class TreeWithSelectionListener extends JFrame implements
		TreeSelectionListener {

	private static final long serialVersionUID = 2775677715679796738L;
	
	JEditorPane editorPane;
	JLabel status = new JLabel();

	public TreeWithSelectionListener() {
		super("TreeWithSelectionListener");
		setBounds(50, 100, 880, 420);

		DefaultMutableTreeNode root = new DefaultMutableTreeNode("资源管理器");
        DefaultMutableTreeNode node = new DefaultMutableTreeNode("TreeWithCRUD.java");
        root.add(node);
        node = new DefaultMutableTreeNode("TreeWithModelListener.java");
        root.add(node);
        node = new DefaultMutableTreeNode("TreeWithSelectionListener.java");
        root.add(node);

        JTree tree = new JTree(root);
        // 设置Tree的选择模式为一次只能选择一个节点
        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        // 检查是否有TreeSelectionEvent事件。
        tree.addTreeSelectionListener(this);
        
        // 下面五行，JSplitPane中，左边是放含有JTree的JScrollPane,右边是放JEditorPane.
        JScrollPane scrollPane1 = new JScrollPane(tree, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        editorPane = new JEditorPane();
        JScrollPane scrollPane2 = new JScrollPane(editorPane,  JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        JSplitPane splitPane = new JSplitPane(
        JSplitPane.HORIZONTAL_SPLIT,true, scrollPane1, scrollPane2);
        splitPane.setDividerSize(1);

        getContentPane().add(splitPane, BorderLayout.CENTER);
        getContentPane().add(splitPane, BorderLayout.CENTER);
        
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
	}
	
	public void valueChanged(TreeSelectionEvent e) {
		JTree tree = (JTree) e.getSource();
		//利用JTree的getLastSelectedPathComponent()方法取得目前选取的节点.
        DefaultMutableTreeNode selNode = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
        String nodeName = selNode.toString();
        if(selNode.isLeaf()) {
        	String filepath = "file:"+System.getProperty("user.dir") +
        		System.getProperty("file.separator") + nodeName;

        	try {
				editorPane.setPage(filepath);
			} catch (IOException e1) {
				status.setText("哎呀呀，文件未发现 ");
				e1.printStackTrace();
			}
        }
	}
	
	public static void main(String[] args) {
		new TreeWithSelectionListener();
	}

}